package com.cutepeer.notes.dialogs;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.cutepeer.lib.Intents;
import com.cutepeer.lib.ads.CutepeerAds;
import com.cutepeer.lib.utils.AppUtils;
import com.cutepeer.lib.utils.NetworkUtils;
import com.cutepeer.lib.utils.TextUtils;
import com.cutepeer.lib.view.Animations;
import com.cutepeer.lib.view.CustomDialog;
import com.cutepeer.lib.view.CustomToast;
import com.cutepeer.libonline.CutepeerSDK;
import com.cutepeer.libonline.R;
import com.cutepeer.libonline.dialogs.ConfigDialog;
import com.cutepeer.libonline.dialogs.DialogChangePassword;
import com.cutepeer.libonline.dialogs.DialogPhotoShare;
import com.cutepeer.libonline.dialogs.DialogPhotoShareGif;
import com.cutepeer.libonline.dialogs.DialogPhotoViewer;
import com.cutepeer.libonline.dialogs.DialogProfileEdit;
import com.cutepeer.libonline.dialogs.DialogSignUp;
import com.cutepeer.libonline.gallery.adapters.PhotoAdapter;
import com.cutepeer.libonline.server.CURL;
import com.cutepeer.libonline.server.KEY;
import com.cutepeer.libonline.server.connect.User;
import com.cutepeer.libonline.services.PhotoShareService;
import com.cutepeer.libonline.settings.UserSigned;
import com.cutepeer.libonline.utils.FileUtils;
import com.cutepeer.notes.MainActivity;
import com.cutepeer.notes.SigninActivity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

/**
 * @since Thursday, November 04, 2014
 * @author hoangcaomobile
 *
 */
@SuppressLint("SetJavaScriptEnabled")
public class DialogMain extends DialogFragment implements OnClickListener {

	private static Activity mActivity;
	private static FragmentManager mFragmentManager;
	private static Dialog mDialog;

	// general
	private static RelativeLayout layoutGuest;
	private static RelativeLayout layoutLogged;
	private static Button btInstallFull;
	// --

	// guest
	private static EditText etSignInAccount;
	private static EditText etSignInPassword;
	//

	// logged
	private static WebView wv;
	private static ProgressBar pb;
	private static IntentFilter mIntentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
	private static String urlCurrent = CURL.URLHome;
	private static boolean isRegisterReceiver = false;
	private static ImageButton ibBack;
	private static ImageButton ibHeaderRight;
	// --

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		mActivity = activity;
		mFragmentManager = getFragmentManager();
		super.onAttach(activity);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mDialog = new Dialog(mActivity, android.R.style.Theme_Translucent_NoTitleBar);
		mDialog.getWindow().getAttributes().windowAnimations = R.style.dialogAnimSlideUpDown;
		mDialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		mDialog.setContentView(R.layout.dialog_main);
		mDialog.show();

		vInit();
		CutepeerSDK.moveButtonTouchToTop();
		// vInitAdmobInterstitial();
		return mDialog;
	}

	private void vInit() {
		layoutGuest = (RelativeLayout) mDialog.findViewById(R.id.layoutGuest);
		layoutLogged = (RelativeLayout) mDialog.findViewById(R.id.layoutLogged);
		btInstallFull = (Button) mDialog.findViewById(R.id.btInstallFull);
		btInstallFull.setVisibility(AppUtils.isAppInstalled(mActivity, "cutepeer.com") ? View.GONE : View.VISIBLE);
		btInstallFull.setOnClickListener(this);
		mDialog.findViewById(R.id.vBottom).setVisibility(AppUtils.isAppInstalled(mActivity, "cutepeer.com") ? View.GONE : View.VISIBLE);

		mDialog.findViewById(R.id.ibHeaderLeft).setOnClickListener(this);
		mDialog.findViewById(R.id.ibHeaderRight).setOnClickListener(this);
		mDialog.findViewById(R.id.btSignUp).setOnClickListener(this);
		mDialog.findViewById(R.id.btSignIn).setOnClickListener(this);
		mDialog.findViewById(R.id.tvLostPassword).setOnClickListener(this);
		mDialog.findViewById(R.id.ibBack).setOnClickListener(this);

		if (UserSigned.isUserLogged(mActivity)) {
			vInitLogged();
		} else {
			vInitGuest();
		}

		if (UserSigned.isUserLogged(mActivity) && !isRegisterReceiver) {
			mActivity.registerReceiver(mBroadcastReceiver, mIntentFilter);
			isRegisterReceiver = true;
		}
	}

	// guest
	private static void vInitGuest() {
		layoutGuest.setVisibility(View.VISIBLE);
		layoutLogged.setVisibility(View.GONE);

		etSignInAccount = (EditText) mDialog.findViewById(R.id.etSignInAccount);
		etSignInPassword = (EditText) mDialog.findViewById(R.id.etSignInPassword);	
		if (!TextUtils.isStringNull(UserSigned.getUserAccount(mActivity))) {
			etSignInAccount.setText(UserSigned.getUserAccount(mActivity));
		}
	}

	public static void vAppendAccountPassword(String account, String password) {
		etSignInAccount.setText(account);
		etSignInPassword.setText(password);
	}

	public static String getAccountSignUp() {
		return etSignInAccount.getText().toString();
	}

	public static String getPasswordSignUp() {
		return etSignInPassword.getText().toString();
	}

	public static void vSignIn(final String account, final String password) {
		CustomDialog.vDialogLoadingShow(mActivity, mActivity.getString(R.string.dialogMessageLoggingIn), true);
		new Thread(new Runnable(){
			@Override
			public void run() {
				final JSONObject jsonObject = User.signIn(
						account,
						password,
						UserSigned.getUserLatitude(mActivity),
						UserSigned.getUserLongitude(mActivity),
						UserSigned.getUserGCMId(mActivity));
				mActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (jsonObject != null) {
							try {
								if (Integer.parseInt(jsonObject.getString(KEY.tagQueryResult)) == KEY.queryResultSuccess) {
									JSONObject jsonUser= jsonObject.getJSONObject(KEY.user);
									UserSigned.vSaveUserInfo(
											mActivity,
											jsonUser.getString(KEY.userId),
											jsonUser.getString(KEY.userAccount),
											password,
											jsonUser.getString(KEY.userName),
											jsonUser.getString(KEY.userCover),
											jsonUser.getString(KEY.userAvatar),
											jsonUser.getString(KEY.userGCMId),
											jsonUser.getString(KEY.userEmail),
											jsonUser.getString(KEY.userGender),
											jsonUser.getString(KEY.userBirthdayDate),
											jsonUser.getString(KEY.userBirthdayMonth),
											jsonUser.getString(KEY.userBirthdayYear),
											jsonUser.getString(KEY.userLanguage),
											jsonUser.getString(KEY.userAddress));

									// sign in success
									mDialog.dismiss();
									mActivity.startActivity(new Intent(mActivity, MainActivity.class));
									SigninActivity.vFinish();
									//									vInitLogged();
									//									wv.loadUrl(urlCurrent);
									//									CutepeerSDK.vInitLoggedUser();
									// --
								} else if (Integer.parseInt(jsonObject.getString(KEY.tagQueryResult)) == KEY.queryResultFailed) {
									CustomToast.vToastShort(mActivity, mActivity.getString(R.string.toastWrongPassword));
									etSignInPassword.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.shake));
									UserSigned.vLogout(mActivity);
								} else if (jsonObject.getString(KEY.tagQueryResult).equals("-1")) {
									CustomToast.vToastShort(mActivity, mActivity.getString(R.string.toastAccountNotFound));
									etSignInAccount.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.shake));
									UserSigned.vLogout(mActivity);
								} else if (jsonObject.getString(KEY.tagQueryResult).equals("-2")) {
									CustomToast.vToastShort(mActivity, jsonObject.getString("message"));
									UserSigned.vLogout(mActivity);
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							CustomToast.vToastCannotConnectToServer(mActivity);
						}
						CustomDialog.vDialogLoadingDismiss();
					}
				});
			}
		}).start();
	}
	// --

	// logged
	private static void vInitLogged() {
		layoutGuest.setVisibility(View.GONE);
		layoutLogged.setVisibility(View.VISIBLE);

		wv = (WebView) mDialog.findViewById(R.id.wv);
		pb = (ProgressBar) mDialog.findViewById(R.id.pb);
		ibBack = (ImageButton) mDialog.findViewById(R.id.ibBack);
		ibHeaderRight = (ImageButton) mDialog.findViewById(R.id.ibHeaderRight);

		wv.getSettings().setJavaScriptEnabled(true);
		wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		wv.getSettings().supportZoom();
		wv.setWebViewClient(new NewWebViewClient());
		wv.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				pb.setVisibility(View.VISIBLE);
				pb.setProgress(0);
				pb.setMax(100);
				pb.incrementProgressBy(progress);
				if (progress == 100) {
					pb.setVisibility(View.GONE);
				}
			}
		});

		urlCurrent = CURL.URLHome + "signin.php?account="
				+ UserSigned.getUserAccount(mActivity) + "&password="
				+ UserSigned.getUserPassword(mActivity) + "&ima=yes";

		vUpdateInfo();
	}

	private static class NewWebViewClient extends WebViewClient {		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (!url.contains("page_check_internet.html")) {
				urlCurrent = url;
			}
			if (url.contains(CURL.URLHome + "index.php?view=photo")) {
				wv.loadUrl(CURL.URLHome);
				vChoosePhoto();
			} else if (url.contains(CURL.URLUserUpdate)) {
				wv.loadUrl(CURL.URLHome);
				if (!ConfigDialog.isDialogFragmentShowing(mFragmentManager, ConfigDialog.dialogProfileEdit)) {
					new DialogProfileEdit().show(mFragmentManager, ConfigDialog.dialogProfileEdit);
				}
			} else if (url.contains(CURL.URLUserSetPass)) {
				wv.loadUrl(CURL.URLHome);
				if (!ConfigDialog.isDialogFragmentShowing(mFragmentManager, ConfigDialog.dialogChangePassword)) {
					new DialogChangePassword().show(mFragmentManager, ConfigDialog.dialogChangePassword);
				}
			} else if (url.contains(CURL.URLUserSignOut)) {
				vSignOut();
			} else if (url.endsWith("jpg") || url.endsWith("jpeg") || url.endsWith("png") || url.endsWith("gif")) {
				if (!ConfigDialog.isDialogFragmentShowing(mFragmentManager, ConfigDialog.dialogPhotoViewer)) {
					DialogPhotoViewer.vSaveRecentPhotoViewer(mActivity, url);
					new DialogPhotoViewer().show(mFragmentManager, ConfigDialog.dialogPhotoViewer);
				}
			}
			ibHeaderRight.setImageResource(R.drawable.ic_spinner_white);
			ibHeaderRight.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.rotate_spinner));
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, final String url) {
			wv.requestFocus();
			if (wv != null && wv.isFocused() && wv.canGoBack()) {
				ibBack.setVisibility(View.VISIBLE);
			} else {
				ibBack.setVisibility(View.GONE);
			}
			ibHeaderRight.setImageResource(R.drawable.ic_more_white);
			ibHeaderRight.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.none));
		}

	}

	public static void vLoadBeforeUrl() {
		if (wv != null && wv.isFocused() && wv.canGoBack()) {
			wv.goBack();
		}
	}

	private static BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			ConnectivityManager connectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
			if (activeNetworkInfo == null) {
				wv.loadUrl("file:///android_asset/page_check_internet.html");
			} else {
				wv.loadUrl(urlCurrent);
				CutepeerSDK.vUpdateCountNotify(0);
			}
		}
	};

	// photo share
	public static boolean isChoosePhoto = false;
	private static void vChoosePhoto() {
		isChoosePhoto = true;
		PhotoAdapter.vChoosePhotoCache(mActivity);
	}
	// --

	public static boolean isEnableDialogSharePhoto = false;
	private void vDialogSharePhoto() {
		if (isEnableDialogSharePhoto) {
			isEnableDialogSharePhoto = false;
			if (PhotoShareService.getPhotoPath(mActivity).length() > 0) {
				if (FileUtils.getFileType(PhotoShareService.getPhotoPath(mActivity)).equals("gif") ||
						FileUtils.getFileType(PhotoShareService.getPhotoPath(mActivity)).equals("GIF")) {
					if (!ConfigDialog.isDialogFragmentShowing(mFragmentManager, ConfigDialog.dialogPhotoShareGif)) {
						new DialogPhotoShareGif().show(mFragmentManager, ConfigDialog.dialogPhotoShareGif);
					}
				} else {
					if (!ConfigDialog.isDialogFragmentShowing(mFragmentManager, ConfigDialog.dialogPhotoShare)) {
						new DialogPhotoShare().show(mFragmentManager, ConfigDialog.dialogPhotoShare);
					}
				}
			}
		}
	}
	// --

	private static void vUpdateInfo() {
		new Thread(new Runnable(){
			@Override
			public void run() {
				final JSONObject jsonObject = User.signIn(
						UserSigned.getUserAccount(mActivity),
						UserSigned.getUserPassword(mActivity),
						UserSigned.getUserLatitude(mActivity),
						UserSigned.getUserLongitude(mActivity),
						UserSigned.getUserGCMId(mActivity));
				mActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (jsonObject != null) {
							try {
								if (Integer.parseInt(jsonObject.getString(KEY.tagQueryResult)) == KEY.queryResultFailed) {
									CustomToast.vToastShort(mActivity,  mActivity.getString(R.string.toastWrongPassword));
									vSignOut();
								}  else if (jsonObject.getString(KEY.tagQueryResult).equals("-1")) {
									CustomToast.vToastShort(mActivity, mActivity.getString(R.string.toastAccountNotFound));
									vSignOut();
								} else if (jsonObject.getString(KEY.tagQueryResult).equals("-2")) {
									CustomToast.vToastShort(mActivity, jsonObject.getString("message"));
									vSignOut();
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							CustomToast.vToastCannotConnectToServer(mActivity);
						}

						new Thread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								FileUtils.vDeleteFolderCache();
							}
						}).start();
					}
				});
			}
		}).start();
	}

	private static void vSignOut() {
		UserSigned.vLogout(mActivity);
		vInitGuest();
		CutepeerSDK.vInitGuest();
		CutepeerSDK.vUpdateCountNotify(0);
	}

	public static void vUpdatePass(String mAccount, String mPassword) {
		wv.loadUrl(CURL.URLHome + "signin.php?account="
				+ mAccount + "&password="
				+ mPassword + "&ima=yes");
	}
	// --

	public static void vRefresh() {
		if (mActivity != null && mBroadcastReceiver != null && mIntentFilter != null) {
			mActivity.registerReceiver(mBroadcastReceiver, mIntentFilter);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.ibHeaderLeft) {
			Animations.vAnimationClick(v);
			dismiss();
		} else if (v.getId() == R.id.ibHeaderRight) {
			Animations.vAnimationClick(v);
			Intents.vCutepeerSoftware(mActivity);
		} else if (v.getId() == R.id.btSignUp) {
			if (!ConfigDialog.isDialogFragmentShowing(mFragmentManager, ConfigDialog.dialogSignUp)) {
				new DialogSignUp().show(mFragmentManager, ConfigDialog.dialogSignUp);
			}

		} else if (v.getId() == R.id.btSignIn) {
			if (NetworkUtils.isInternetConnected(mActivity)) {
				if (etSignInAccount.length() > 0 & etSignInPassword.length() > 0) {
					vSignIn(etSignInAccount.getText().toString(), etSignInPassword.getText().toString());
				} else {
					Animation shake = AnimationUtils.loadAnimation(mActivity, R.anim.shake);
					if (etSignInAccount.length() == 0) {
						etSignInAccount.startAnimation(shake);
					}
					if (etSignInPassword.length() == 0) {
						etSignInPassword.startAnimation(shake);
					}
				}
			} else {
				CustomToast.vToastNoInternet(mActivity);
			}
		} else if (v.getId() == R.id.tvLostPassword) {
			Animations.vAnimationClick(v);
			Intents.vOpenUrl(mActivity, CURL.URLUserLostPass);
		} else if (v.getId() == R.id.ibBack) {
			if (UserSigned.isUserLogged(mActivity) && wv.isFocused() && wv.canGoBack()) {
				Animations.vAnimationClick(v);
				wv.goBack();
			}
		} else if (v.getId() == R.id.btInstallFull) {
			Intents.vOpenAppOnGooglePlay(mActivity, "cutepeer.com");
		}
	}
	// --	

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		vDialogSharePhoto();
		isChoosePhoto = false;
		super.onStart();
	}


	@Override
	public void onDismiss(DialogInterface dialog) {
		// TODO Auto-generated method stub
		CutepeerSDK.moveButtonTouchToCurrent();
		if (isRegisterReceiver) {
			try {
				mActivity.unregisterReceiver(mBroadcastReceiver);
				isRegisterReceiver = false;
			} catch (Exception e) {
				Log.e("unregisterReceiver", e.getMessage());
			}
		}
		super.onDismiss(dialog);
	}

	private void vInitAdmobInterstitial() {
		final InterstitialAd mInterstitial = new InterstitialAd(mActivity);
		mInterstitial.setAdUnitId(getString(R.string.adsIdInterstitial));
		mInterstitial.loadAd(new AdRequest.Builder().build());
		mInterstitial.setAdListener(new AdListener() {

			@Override
			public void onAdLoaded() {
				// TODO Auto-generated method stub
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (mInterstitial.isLoaded()) {
							mInterstitial.show();
						}
					}
				}, CutepeerAds.timeDelayToShowAdmobInterstitial2);
				super.onAdLoaded();
			}

			@Override
			public void onAdClosed() {
				// TODO Auto-generated method stub
				super.onAdClosed();
			}

		});
	}

}

